package com.leetcode.LeetCode精选TOP面试题;

/**
 * @author 覃国强
 * @date 2022-07-06 17:58
 */
public class 题库_0200_岛屿数量 {

  static
  class Solution {

    private static final int[][] nexts = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};

    public int numIslands(char[][] grid) {
      int answer = 0;
      for (int i = 0; i < grid.length; ++i) {
        for (int j = 0; j < grid[0].length; ++j) {
          if (grid[i][j] == '1') {
            ++answer;
            dfs(grid, i, j);
          }
        }
      }
      return answer;
    }

    private void dfs(char[][] grid, int i, int j) {
      if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') {
        return;
      }
      grid[i][j] = '0';
      for (int[] next : nexts) {
        dfs(grid, i + next[0], j + next[1]);
      }
    }
  }

}
